package com.jhgsys.internal.accident.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jhgsys.internal.accident.dto.AccidentAlertsDto;
import com.jhgsys.internal.accident.entity.AccidentAlerts;
import com.jhgsys.internal.accident.entity.AccidentAlertsFile;
import com.jhgsys.internal.accident.mapper.AccidentAlertsMapper;
import com.jhgsys.internal.accident.service.IAccidentAlertsFileService;
import com.jhgsys.internal.accident.service.IAccidentAlertsService;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.utils.BeanHelper;
import com.jhgsys.internal.common.utils.DateUtil;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.system.entity.Tenant;
import com.jhgsys.internal.system.service.ITenantService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * 安全警报 Service实现
 *
 * @author zhangwei
 * @date 2024-08-22 09:19:50
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class AccidentAlertsServiceImpl extends ServiceImpl<AccidentAlertsMapper, AccidentAlerts> implements IAccidentAlertsService {

    @Autowired
    private IAccidentAlertsFileService accidentAlertsFileService;

    @Autowired
    private ITenantService tenantService;

    /**
     * 查询（分页）
     * @author zhangwei
     * @date 2024-08-22 09:19:50
     * @param request QueryRequest
     * @param accidentAlertsDto accidentAlertsDto
     * @return IPage<AccidentAlerts>
     */
    @Override
    public IPage<AccidentAlerts> findAccidentAlertsPage(QueryRequest request, AccidentAlertsDto accidentAlertsDto) {
        LambdaQueryWrapper<AccidentAlerts> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AccidentAlerts::getDeletedFlg, 0);
        if(StringUtils.isNotBlank(accidentAlertsDto.getAlertsTitle())){
            queryWrapper.like(AccidentAlerts::getAlertsTitle,accidentAlertsDto.getAlertsTitle());
        }
        if(StringUtils.isNotBlank(accidentAlertsDto.getTenantId())){
            queryWrapper.eq(AccidentAlerts::getTenantId,accidentAlertsDto.getTenantId());
        }
        if(StringUtils.isNotBlank(accidentAlertsDto.getAlertsType())){
            queryWrapper.eq(AccidentAlerts::getAlertsType,accidentAlertsDto.getAlertsType());
        }
        if(StringUtils.isNotBlank(accidentAlertsDto.getPublishStartDate()) && StringUtils.isNotBlank(accidentAlertsDto.getPublishEndDate()) ){
            Date startDate = DateUtil.parseDate(accidentAlertsDto.getPublishStartDate(),DateUtil.FULL_TIME_SPLIT_PATTERN);
            Date endDate = DateUtil.parseDate(accidentAlertsDto.getPublishEndDate(),DateUtil.FULL_TIME_SPLIT_PATTERN);
            queryWrapper.between(AccidentAlerts::getPublishDate,startDate,endDate);
        }
        // TODO 设置查询条件
        Page<AccidentAlerts> page = new Page<>(request.getPageNum(), request.getPageSize());
        FebsUtil.pageWrapper(page, request);
        IPage<AccidentAlerts> pages = this.page(page,queryWrapper);
        return pages;
    }

    /**
     * 查询（分页）
     * @author zhangwei
     * @date 2024-08-22 09:19:50
     * @param request QueryRequest
     * @param accidentAlertsDto accidentAlertsDto
     * @return IPage<AccidentAlerts>
    */
    @Override
    public IPage<AccidentAlertsDto> findAccidentAlertsDtoPage(QueryRequest request, AccidentAlertsDto accidentAlertsDto) {
        IPage<AccidentAlertsDto> result = new Page<>(request.getPageNum(), request.getPageSize());
        LambdaQueryWrapper<AccidentAlerts> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AccidentAlerts::getDeletedFlg, 0);
        if(StringUtils.isNotBlank(accidentAlertsDto.getTenantId())){
            queryWrapper.eq(AccidentAlerts::getTenantId,accidentAlertsDto.getTenantId());
        }
        if(StringUtils.isNotBlank(accidentAlertsDto.getAlertsTitle())){
            queryWrapper.like(AccidentAlerts::getAlertsTitle,accidentAlertsDto.getAlertsTitle());
        }
        if(StringUtils.isNotBlank(accidentAlertsDto.getAlertsType())){
            queryWrapper.eq(AccidentAlerts::getAlertsType,accidentAlertsDto.getAlertsType());
        }
        if(StringUtils.isNotBlank(accidentAlertsDto.getPublishStartDate()) && StringUtils.isNotBlank(accidentAlertsDto.getPublishEndDate()) ){
            Date startDate = DateUtil.parseDate(accidentAlertsDto.getPublishStartDate(),DateUtil.FULL_TIME_SPLIT_PATTERN);
            Date endDate = DateUtil.parseDate(accidentAlertsDto.getPublishEndDate(),DateUtil.FULL_TIME_SPLIT_PATTERN);
            queryWrapper.between(AccidentAlerts::getPublishDate,startDate,endDate);
        }
        // TODO 设置查询条件
        Page<AccidentAlerts> page = new Page<>(request.getPageNum(), request.getPageSize());
        FebsUtil.pageWrapper(page, request);
        IPage<AccidentAlerts> pages = this.page(page,queryWrapper);
        List<AccidentAlerts> alertsList = pages.getRecords();
        List<AccidentAlertsDto> alertsDtoList = new ArrayList<>();
        alertsList.forEach(p -> {
            AccidentAlertsDto alertsDto = BeanHelper.copyProperties(p,AccidentAlertsDto.class);
            Tenant tenant = tenantService.findTenantByTenantId(p.getTenantId());
            alertsDto.setTenantName(Optional.ofNullable(tenant).map(Tenant::getTenantName).orElse(""));
            alertsDtoList.add(alertsDto);
        });
        result.setRecords(alertsDtoList);
        result.setTotal(alertsDtoList.size());
        return result;
    }

    /**
     * 查询（所有）
     * @author zhangwei
     * @date 2024-08-22 09:19:50
     * @param accidentAlerts accidentAlerts
     * @return List<AccidentAlerts>
     */
    @Override
    public List<AccidentAlerts> findAccidentAlertsList(AccidentAlerts accidentAlerts) {
	    LambdaQueryWrapper<AccidentAlerts> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AccidentAlerts::getDeletedFlg, 0);
		// TODO 设置查询条件
		return this.baseMapper.selectList(queryWrapper);
    }

    /**
    * 根据ID查询
    * @author zhangwei
    * @date 2024-08-22 09:19:50
    * @param id
    * @return AccidentAlerts
    */
    @Override
    public AccidentAlertsDto findAccidentAlertsById(String id){
        AccidentAlerts accidentAlerts = this.baseMapper.selectById(id);
        if(accidentAlerts != null){
            AccidentAlertsDto accidentAlertsDto = BeanHelper.copyProperties(accidentAlerts,AccidentAlertsDto.class);
            accidentAlertsDto.setAccidentAlertsFileList(accidentAlertsFileService.list(new LambdaQueryWrapper<AccidentAlertsFile>()
                    .eq(AccidentAlertsFile::getAlertsId,accidentAlertsDto.getAlertsId())));
            return accidentAlertsDto;
        }
        return new AccidentAlertsDto();
    }

    /**
     * 新增
     * @author zhangwei
     * @date 2024-08-22 09:19:50
     * @param accidentAlerts accidentAlerts
     */
    @Override
    @Transactional
    public void createAccidentAlerts(AccidentAlerts accidentAlerts,List<AccidentAlertsFile> fileList) {
        accidentAlerts.setCreatedTime(new Date());
        this.save(accidentAlerts);
        if(!CollectionUtils.isEmpty(fileList)){
            fileList.forEach(i->{
                i.setAlertsId(accidentAlerts.getAlertsId());
                i.setTenantId(accidentAlerts.getTenantId());
                i.setCreatedTime(new Date());
                i.setCreatedBy(accidentAlerts.getCreatedBy());
            });
            this.saveAccidentAlertsFiles(fileList, accidentAlerts.getAlertsId());
        }
    }

    /**
     * 修改
     * @author zhangwei
     * @date 2024-08-22 09:19:50
     * @param accidentAlerts accidentAlerts
     */
    @Override
    @Transactional
    public void updateAccidentAlerts(AccidentAlerts accidentAlerts,List<AccidentAlertsFile> fileList) {
        accidentAlerts.setUpdatedTime(new Date());
        this.saveOrUpdate(accidentAlerts);
        if(!CollectionUtils.isEmpty(fileList)){
            fileList.forEach(i->{
                i.setAlertsId(accidentAlerts.getAlertsId());
                i.setTenantId(accidentAlerts.getTenantId());
                i.setCreatedTime(new Date());
                i.setCreatedBy(accidentAlerts.getCreatedBy());
            });
            this.saveAccidentAlertsFiles(fileList, accidentAlerts.getAlertsId());
        }
    }

    /**
     * 逻辑删除
     * @author zhangwei
     * @date 2024-08-22 09:19:50
     * @param accidentAlerts accidentAlerts
     * @param accidentAlertsIds accidentAlertsIds
     */
    @Override
    @Transactional
    public void deleteAccidentAlerts(AccidentAlerts accidentAlerts,String accidentAlertsIds) {
        List<String> list = Arrays.asList(accidentAlertsIds.split(StringPool.COMMA));
        this.baseMapper.update(accidentAlerts,new LambdaQueryWrapper<AccidentAlerts>().in(AccidentAlerts::getAlertsId,list));
	}

    /**
    * 物理删除
    * @author zhangwei
    * @date 2024-08-22 09:19:50
    * @param accidentAlertsIds accidentAlertsIds
    */
    @Override
    @Transactional
    public void physicallyDeleteAccidentAlerts(String accidentAlertsIds) {
        List<String> list = Arrays.asList(accidentAlertsIds.split(StringPool.COMMA));
        LambdaQueryWrapper<AccidentAlerts> wapper = new LambdaQueryWrapper<>();
        wapper.in(AccidentAlerts::getAlertsId,list);
        this.remove(wapper);
    }

    @Override
    public void saveAccidentAlertsFiles(List<AccidentAlertsFile> fileList,String alertsId) {
        accidentAlertsFileService.deleteByAlertIds(alertsId);
        accidentAlertsFileService.saveBatch(fileList);
    }
}
